#include "camera.h"
#include<stdio.h>
#include <sys/types.h>       
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <json-c/json.h>
#include <unistd.h>
#include "node.h"
#include <string.h>
#include "app.h"
#define TCPPORT 8000
#define IP "0.0.0.0"    //云服务器的内网ip
pthread_mutex_t mutex;
node*head=NULL;
char*newbuffer=NULL;
int vedio_real_len;
void*Client_deal(void*arg)
{
   int fd=*(int*)arg;
   char buffer[128]={0};
   int recv_size;
  
   while(1)
   {
      recv_size=recv(fd,buffer,sizeof(buffer),0);
      if(recv_size<0)
      {
         printf("recv error");
         exit(1);


      }
      else if(recv_size==0)
      {
        printf("客户端已下线：%d\n",fd);
        exit(2);

      }
    
      struct json_object*obj=json_tokener_parse(buffer);
      struct json_object*val=json_object_object_get(obj,"cmd");//读取"cmd"对应的val是"info" "control" "get_video_data"
      const char*buf=(const char*)json_object_get_string(val);//转化为字符串
      if(!strcmp(buf,"info"))  //摄像头上线请求
      {
            send_camera(fd,obj);
      }
      else if(!strcmp(buf,"control"))//app发送控制请求
      {

           send_control(obj);

      }
      else if(!strcmp(buf,"get_video_data"))//app上线发送获取视频数据请求
      {
           deal_vedio_to_app(fd);//该fd是来区别是哪一个客户端连接的

        
      }


   }






}

int main()
{
   initlsit();
   newbuffer=(char*)malloc (VEDIOLEN);
   pthread_mutex_init(&mutex,NULL);
   printf("3333333333\n");
   int sockfd=socket(AF_INET,SOCK_STREAM,0);//创建socket套接字
   if(sockfd<0)
   {
      printf("socket error");
      exit(3);

   }
    struct sockaddr_in server;
    server.sin_family=AF_INET;
    server.sin_port=htons(TCPPORT);
    server.sin_addr.s_addr=inet_addr(IP);
    int t=1;
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&t,sizeof(t));//设置地址可以被复用


   if(bind(sockfd,(const struct sockaddr*)&server,sizeof(server))<0) //绑定
   {
    printf("bind error");
    exit(4);
 
   }
   printf("4444444444444\n");
   if(listen(sockfd,10)<0)//监听是否有链接，第二个为全连接队列长度
   {
    printf("listen error");
    exit(5);

   }
   printf("555555555\n");

   struct sockaddr_in client;
   int len=sizeof(client);
   while(1)
   {

    int fd=accept(sockfd,(struct sockaddr*)&client,&len);//获取连接的客户端fd
    //创建多线程来处理来自摄像头上线，app上线请求视频，app发送控制请求
    pthread_t tid;
    pthread_create(&tid,NULL,Client_deal,&fd);//文件操作符传过去

    usleep(100000);
   
   }



}